<?php
/**
 * Plugin Apis: Create the summary of a hive and create a form to add a hive manipulation
 *
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author     Monika Dispas <monika@dispas.be>
 * @author     Philippe Bajoit <philippe@bajoit.net>
 */
// must be run within Dokuwiki
if (!defined('DOKU_INC')) die();

if (!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
require_once(DOKU_PLUGIN.'syntax.php');

if (!function_exists('date_create_from_format')) {
	function date_create_from_format($f, $d) {
		if (strcmp($f,'Ymd') == 0) {
			$year  = substr($d, 0, 4);
			$month = substr($d, 4, 2);
			$day   = substr($d, 6, 2);
			return new DateTime("$year-$month-$day");
		} else if (strcmp($f,'Y-m-d') == 0) {
			$year  = substr($d, 0, 4);
			$month = substr($d, 5, 2);
			$day   = substr($d, 8, 2);
			return new DateTime("$year-$month-$day");
		}
		echo 'NOT IMPLEMENTED FORMAT for my date_create_from_format';
	}
}

function format_json($json, $html = false, $tabspaces = null)
{
	$tabcount = 0;
	$result = '';
	$inquote = false;
	$ignorenext = false;

	if ($html) {
		$tab = str_repeat("&nbsp;", ($tabspaces == null ? 4 : $tabspaces));
		$newline = "<br/>";
	} else {
		$tab = ($tabspaces == null ? "\t" : str_repeat(" ", $tabspaces));
		$newline = "\n";
	}

	for($i = 0; $i < strlen($json); $i++) {
		$char = $json[$i];

		if ($ignorenext) {
			$result .= $char;
			$ignorenext = false;
		} else {
			switch($char) {
				case ':':
					$result .= $char . (!$inquote ? " " : "");
					break;
				case '{':
					if (!$inquote) {
						$tabcount++;
						$result .= $char . $newline . str_repeat($tab, $tabcount);
					}
					else {
						$result .= $char;
					}
					break;
				case '}':
					if (!$inquote) {
						$tabcount--;
						$result = trim($result) . $newline . str_repeat($tab, $tabcount) . $char;
					}
					else {
						$result .= $char;
					}
					break;
				case ',':
					if (!$inquote) {
						$result .= $char . $newline . str_repeat($tab, $tabcount);
					}
					else {
						$result .= $char;
					}
					break;
				case '"':
					$inquote = !$inquote;
					$result .= $char;
					break;
				case '\\':
					if ($inquote) $ignorenext = true;
					$result .= $char;
					break;
				default:
					$result .= $char;
			}
		}
	}

	return $result;
}

require_once('queenFamily.php');

/**
 * All DokuWiki plugins to extend the parser/rendering mechanism
 * need to inherit from this class
*/
class syntax_plugin_apis extends DokuWiki_Syntax_Plugin {

	/**
	 * What kind of syntax are we?
	 */
	function getType() {
		return 'substition';
	}

	/**
	 * What about paragraphs?
	 */
	function getPType(){
		return 'block';
	}

	/**
	 * Where to sort in?
	 */
	function getSort(){
		return 32; 					// ??? 155 ???
	}

	/**
	 * Connect pattern to lexer
	 */
	function connectTo($mode) {
		$this->Lexer->addSpecialPattern('\[APIS.*?\]',$mode,'plugin_apis');
	}

	/**
	 * Handle the match
	 */
	function handle($match, $state, $pos, &$handler) {
		$match = substr($match,1,-1); // remove []
		$tks = explode(" ", $match);

		return $tks;
	}

	/**
	 * Create output
	 */
	function render($mode, &$R, $data) {
		if ($mode != 'xhtml')
			return false;

		$R->info['cache'] = false; // don't cache
		list($token, $x) = $data;

		if ($token == 'APIS-HIVE') {
			$R->doc .= $this->render_apis_hive($x);
		} elseif ($token == 'APIS-SUMMARY') {
			$R->doc .= $this->render_apis_summary();
		} elseif ($token == 'APIS-EVAL') {
			$R->doc .= $this->render_apis_eval($x);
		} elseif ($token == 'APIS-TREE') {
			$R->doc .= $this->render_apis_tree($x);
		}
		return true;
	}

	private function render_apis_hive($name) {
		global $INFO;
		global $ID;

		$ret = '';
		
		// read json file
		$json_a = json_decode(rawWiki('json:'.$name), true);

		// save datas
        if (isset($_POST['apis_id'])) {
			$changed = false;
			if (isset($_POST['hive_type']) && ($json_a["hive"]["type"] != $_POST['hive_type'])) {
				$json_a["hive"]["type"] = $_POST['hive_type'];
				$changed = true;
			}
			if (isset($_POST['queen_number']) && ($json_a["queen"]["number"] != $_POST['queen_number'])) {
				$json_a["queen"]["number"] = $_POST['queen_number'];
				$changed = true;
			}
			if (isset ($_POST['queen_birth']) && ($json_a["queen"]["birth"] != $_POST['queen_birth'])) {
				$json_a["queen"]["birth"] = $_POST['queen_birth'];
				$changed = true;
			}
			if (isset($_POST['hive_frame_count']) && ($json_a["hive"]["frame_count"] != $_POST['hive_frame_count'])) {
				$json_a["hive"]["frame_count"] = $_POST['hive_frame_count'];
				$changed = true;
			}
			if (isset($_POST['super_frame_count']) || isset($_POST['super_start_date']) || isset($_POST['super_end_date'])) {
				$changed = true;

				$j = 0;
				for ($i = 0; $i < count($_POST['super_frame_count']); $i++) {
					if (($_POST['super_frame_count'][$i] != '')
					 || ($_POST['super_start_date'][$i] != '')
					 || ($_POST['super_end_date'][$i] != '')) {
						$json_a["super"][$j]["frame-count"] = $_POST['super_frame_count'][$i];
						$json_a["super"][$j]["start-date"]  = $_POST['super_start_date'][$i];
						$json_a["super"][$j]["end-date"]    = $_POST['super_end_date'][$i];
						$j++;
					}
				}
			}
			if (isset($_POST['feed_quantity']) || isset($_POST['feed_type']) || isset($_POST['feed_start_date'])) {
				$changed = true;

				$j = 0;
				for ($i = 0; $i < count($_POST['feed_quantity']); $i++) {
					if (($_POST['feed_quantity'][$i] != '')
					 && ($_POST['feed_type'][$i] != '')
					 && ($_POST['feed_start_date'][$i] != '')) {
						$json_a["feed"][$j]["quantity"]   = $_POST['feed_quantity'][$i];
						$json_a["feed"][$j]["type"]       = $_POST['feed_type'][$i];
						$json_a["feed"][$j]["start-date"] = $_POST['feed_start_date'][$i];
						$j++;
					}
				}
			}
			if (isset($_POST['varroa_quantity']) || isset($_POST['varroa_medoc']) || isset($_POST['varroa_start_date']) || isset($_POST['varroa_end_date'])) {
				$changed = true;

				$j = 0;
				for ($i = 0; $i < count($_POST['varroa_quantity']); $i++) {
					if (($_POST['varroa_quantity'][$i] != '')
					 || ($_POST['varroa_medoc'][$i] != '')
					 || ($_POST['varroa_start_date'][$i] != '')
					 || ($_POST['varroa_end_date'][$i] != '')) {
						$json_a["varroa"][$j]["quantity"]   = $_POST['varroa_quantity'][$i];
						$json_a["varroa"][$j]["medication"] = $_POST['varroa_medoc'][$i];
						$json_a["varroa"][$j]["start-date"] = $_POST['varroa_start_date'][$i];
						$json_a["varroa"][$j]["end-date"]   = $_POST['varroa_end_date'][$i];
						$j++;
					}
				}
			}
			if ($changed) {
				$jsonnewfilecontent = format_json(json_encode($json_a));//json_encode($json_a, JSON_PRETTY_PRINT);

				saveWikiText('json:'.$name, $jsonnewfilecontent,
					sprintf($this->lang[$lang_key], 'json:'.$name, 'json:'.$name));

				$ret .= '<div class="success">json:'.$name.'.txt saved</div>';
			}
		}

		$ret .= '<div id="apis__plugin"><h1>Lign&eacute;e '.$json_a["number"].' : '.$json_a["name"].'</h1>
				<h2 class="sectionedit0 ">Description</h2>
				<div id="toggle-view">
					<div class="level2">
						<ul>';

		if (isset($INFO['userinfo']) and isset($_POST['apis_queen'])) {
	        $form = new Doku_Form(array(
				'class' => 'button btn_secedit apis__plugin',
				'id'    => 'apis__plugin' . $this->form_id));
			$form->addHidden('apis_id', $ID);
			$form->addElement(form_makeListboxField(
				'hive_type', // name 
				array('Ruche', 'Ruchette', 'Apidéa'), // values
				$json_a["hive"]["type"], // selected
				'Type :')); // label
			$form->addElement(form_makeTextField(
				'queen_number', // name
				$json_a["queen"]["id"], // value
				'Reine # :')); // label
			$form->addElement(form_makeTextField(
				'queen_birth', // name
				$json_a["queen"]["birth"], // value
				'n&eacute;e le : ')); // label
			$form->addElement(form_makeTextField(
				'hive_frame_count', // name
				$json_a["hive"]["frame_count"], // value
				'Nombre de cadres : ')); // label

			/* visit
			$form->addElement(form_makeTextField(
				'visit_date', // name
				date("Ymd"), // value
				'Date de la visite : ')); // label
			$form->addElement('<br />');
			$form->addElement(form_makeCheckboxField(
				'visit_queen_seen' // name
				,'1' // value
				,'Vu la reine : ' // label
				,'' // id
				,'apis__plugin_checkbox' // class
				//,array('checked' => 'yes')); // attrs
				));
			$form->addElement(form_makeCheckboxField(
				'visit_eggs_seen' // name
				,'1' // value
				,'Vu des oeufs : ' // label
				,'' // id
				,'apis__plugin_checkbox' // class
				)); 
			$form->addElement(form_makeCheckboxField(
				'visit_larva_seen', // name
				'1', // value
				'Vu des larves : ', // label
				'', // id
				'apis__plugin_checkbox' // class
				)); 
			$form->addElement(form_makeTextField(
				'visit_food_frames', // name
				'', // value
				'Nombre de cadres de nourriture : ')); // label
			$form->addElement(form_makeTextField(
				'visit_larva_frames', // name
				'', // value
				'Nombre de cadres de couvain : ')); // label
			$form->addElement(form_makeTextField(
				'visit_queen_cells', // name
				'', // value
				'Nombre de cellules royales : ')); // label

			$form->addElement('Wiki de la visite :<br />');
			$form->addElement(form_makeWikiText(''));*/
			$form->addElement('<br /><br />');
			$form->addElement(form_makeButton('submit', '', 'Sauver'));

			$ret .= 
				'<div class="secedit editbutton_section editbutton_0">'
					.$form->getForm()
				.'</div><hr />';
		}
		else {
			$qid = $json_a["queen"]["id"];
			$ddn = date_create_from_format('Ymd',$json_a["queen"]["birth"]);
			
			$qf = new queenFamily('config-queens');
			$qmdef = null;
			if ($qf->getQueen($qid) != null) {
				$qdef = $qf->getQueen($qid);
				$qmdef = $qf->getAncestor($qdef);
				if (! isset($qmdef['url'])) { $qmdef = null; }
				$ddn = date_create_from_format('Y-m-d',$qdef["birth"]);
			}
			$birthDate = date_format($ddn, 'd-m-Y');
			
			// compute color from birth Year
			$qColor = queenColor(date_format($ddn, 'Y'));
			$qColorBg = queenColorBg($qColor);
				
			$ret .= '
				<li class="level1"><div class="li">Type : <strong>'.$json_a["hive"]["type"].'</strong> '.
				$json_a["hive"]["frame_count"].' cadres</div></li>
				<li class="level1"><div class="li">Reine : 
					<strong style="color:'.$qColor.';'.
					(($qColorBg != null) ? 'background-color:'.$qColorBg.';': '').'">'
					.$json_a["queen"]["id"].'</strong> n&eacute;e le <strong>'.$birthDate.'</strong>'.
					 (($qmdef != null)?'<ul><li class="level2"><div class="li">fille de <a href="'.$qmdef['url'].'">'.$qmdef['name'].'</a></div></li></ul>':'').
					 '</div></li>';
		}

		// Hausse
		$ret .= '<li class="level1 toggle"><div class="li"><span>+</span> Hausse : ';

		if (isset($INFO['userinfo']) and isset($_POST['apis_hive'])) {
	        $form = new Doku_Form(array(
				'class' => 'button btn_secedit apis__plugin',
				'id'    => 'apis__plugin' . $this->form_id));
			$form->addHidden('apis_id', $ID);

			$form->addElement('<br />
				<table>
					<tr>
						<th>Nombre de cadres</th>
						<th>Depuis le</th>
						<th>Jusqu\'au</th>
					</tr>');
			foreach ($json_a["super"] as $hausse) {
				$form->addElement('<tr><td>');
				$form->addElement(form_makeTextField(
					'super_frame_count[]', // name
					$hausse["frame-count"],  // value
					'')); // label
				$form->addElement('</td><td>');
				$form->addElement(form_makeTextField(
					'super_start_date[]', // name
					$hausse["start-date"], // value
					'')); // label
				$form->addElement('</td><td>');
				$form->addElement(form_makeTextField(
					'super_end_date[]', // name
					$hausse["end-date"], // value
					'')); // label
				$form->addElement('</td></tr>');
			}
			$form->addElement('<tr><td>');
			$form->addElement(form_makeTextField(
				'super_frame_count[]', // name
				'', // value
				'')); // label
			$form->addElement('</td><td>');
			$form->addElement(form_makeTextField(
				'super_start_date[]', // name
				'', // value
				'')); // label
			$form->addElement('</td><td>');
			$form->addElement(form_makeTextField(
				'super_end_date[]', // name
				'', // value
				'')); // label
			$form->addElement('</td></tr></table><br />');

			$form->addElement(form_makeButton('submit', '', 'Sauver'));

			$ret .= 
				'<div class="secedit editbutton_section editbutton_0">'
					.$form->getForm()
				.'</div><hr />';
		}
		else if (empty($json_a["super"])) {
			$ret .= '-';
		}
		else {
			$ret .= '<div class="panel"><ul>';
			foreach ($json_a["super"] as $hausse) {
				$ret .= '<li class="level2"><div class="li">'
					.date_format(date_create_from_format('Ymd',$hausse["start-date"]), 'd-m-Y')
					.($hausse["end-date"] != '' ? ' &rarr; '.date_format(date_create_from_format('Ymd',$hausse["end-date"]), 'd-m-Y') : '').' : '
					.'<strong>'.$hausse["frame-count"].'</strong> cadres</div></li>';
			}
			$ret .= '</ul></div>';
		}
		$ret .= '</li>';

		// Nourrissement
		$ret .= '<li class="level1"><div class="li">Nourrissement : ';
		if (isset($INFO['userinfo']) and isset($_POST['apis_feed'])) {
	        $form = new Doku_Form(array(
				'class' => 'button btn_secedit apis__plugin',
				'id'    => 'apis__plugin' . $this->form_id));
			$form->addHidden('apis_id', $ID);

			$form->addElement('<br />
				<table>
					<tr>
						<th>Quantit&eacute;</th>
						<th>Type</th>
						<th>Le</th>
					</tr>');
			foreach ($json_a["feed"] as $nour) {
				$form->addElement('<tr><td>');
				$form->addElement(form_makeTextField(
					'feed_quantity[]', // name
					$nour["quantity"],  // value
					'')); // label
				$form->addElement('</td><td>');				
				$form->addElement(form_makeListboxField(
					'feed_type[]', // name 
					array('Sirop','50/50','Sirop (pillé)'), // values
					$nour["type"], // selected
					'')); // label
				/*
				$form->addElement(form_makeTextField(
					'feed_type[]', // name
					$nour["type"], // value
					'')); // label
				*/
				$form->addElement('</td><td>');
				$form->addElement(form_makeTextField(
					'feed_start_date[]', // name
					$nour["start-date"], // value
					'')); // label
				$form->addElement('</td></tr>');
			}
			$form->addElement('<tr><td>');
			$form->addElement(form_makeTextField(
				'feed_quantity[]', // name
				'', // value
				'')); // label
			$form->addElement('</td><td>');
			$form->addElement(form_makeListboxField(
				'feed_type[]', // name 
				array('Sirop','50/50'), // values
				'', // selected
				'')); // label
			/*
			$form->addElement(form_makeTextField(
				'feed_type[]', // name
				'', // value
				'')); // label
			*/
			$form->addElement('</td><td>');
			$form->addElement(form_makeTextField(
				'feed_start_date[]', // name
				'', // value
				'')); // label
			$form->addElement('</td></tr></table><br />');

			$form->addElement(form_makeButton('submit', '', 'Sauver'));

			$ret .= 
				'<div class="secedit editbutton_section editbutton_0">'
					.$form->getForm()
				.'</div><hr />';
		} 
		else if (empty($json_a["feed"])) {
			$ret .= '-';
		}
		else {
			$ret .= '<ul>';
			$feeds = array();
			foreach ($json_a["feed"] as $nour) {
				$q_ml = 0;
				if (isset($feeds[$nour['type']])) {
					$q_ml = $feeds[$nour['type']];
				}
				if (preg_match('/([0-9]+)x[[:space:]]([0-9]+)[[:space:]]ml/', 
							$nour['quantity'],
							$parts)) {
					$q_ml += $parts[1]*$parts[2];
				} else if (preg_match('/([0-9]+)x[[:space:]]([0-9]+)ml/',
							$nour['quantity'],
							$parts)) {
					$q_ml += $parts[1]*$parts[2];
				} else if (preg_match('/([0-9]+)[[:space:]]ml/',
							$nour['quantity'],
							$parts)) {
					$q_ml += $parts[1];
				} else if (preg_match('/([0-9]+)ml/',
							$nour['quantity'],
							$parts)) {
					$q_ml += $parts[1];
				} else {
					$ret .= 'Warning : UNMATCH '.$nour['quantity'].'<br />';
				}
				$feeds[$nour['type']] = $q_ml;

				$ret .= '<li class="level2"><div class="li">'
					.date_format(date_create_from_format('Ymd',$nour["start-date"]), 'd-m-Y').' : '
					.'<strong>'.$nour["type"].'</strong> / '
					.$nour["quantity"].'</div></li>';
			}
			$ret .= '</ul>';

			foreach ($feeds as $t => $q) {
				$ret .= '<strong>Total : </strong>'.$t.' / '.$q.' ml<br />';
			}
		}
		$ret .= '</li>';

		// Varroa
		$ret .= '<li class="level1"><div class="li">Varroa : ';
		if (isset($INFO['userinfo']) and isset($_POST['apis_varroa'])) {
	        $form = new Doku_Form(array(
				'class' => 'button btn_secedit apis__plugin',
				'id'    => 'apis__plugin' . $this->form_id));
			$form->addHidden('apis_id', $ID);

			$form->addElement('<br />
				<table>
					<tr>
						<th>Quantit&eacute;</th>
						<th>Type</th>
						<th>Du</th>
						<th>Au</th>
					</tr>');
			foreach ($json_a["varroa"] as $varroa) {
				$form->addElement('<tr><td>');
				$form->addElement(form_makeTextField(
					'varroa_quantity[]', // name
					$varroa["quantity"],  // value
					'')); // label
				$form->addElement('</td><td>');
				$form->addElement(form_makeTextField(
					'varroa_medoc[]', // name
					$varroa["medication"], // value
					'')); // label
				$form->addElement('</td><td>');
				$form->addElement(form_makeTextField(
					'varroa_start_date[]', // name
					$varroa["start-date"], // value
					'')); // label
				$form->addElement('</td><td>');
				$form->addElement(form_makeTextField(
					'varroa_end_date[]', // name
					$varroa["end-date"], // value
					'')); // label
				$form->addElement('</td></tr>');
			}
			$form->addElement('<tr><td>');
			$form->addElement(form_makeTextField(
				'varroa_quantity[]', // name
				'', // value
				'')); // label
			$form->addElement('</td><td>');
			$form->addElement(form_makeTextField(
				'varroa_medoc[]', // name
				'', // value
				'')); // label
			$form->addElement('</td><td>');
			$form->addElement(form_makeTextField(
				'varroa_start_date[]', // name
				'', // value
				'')); // label
			$form->addElement('</td><td>');
			$form->addElement(form_makeTextField(
				'varroa_end_date[]', // name
				'', // value
				'')); // label
			$form->addElement('</td></tr></table><br />');

			$form->addElement(form_makeButton('submit', '', 'Sauver'));

			$ret .= 
				'<div class="secedit editbutton_section editbutton_0">'
					.$form->getForm()
				.'</div><hr />';
		} 
		else if (empty($json_a["varroa"])) {
			$ret .= '-';
		}
		else {
			$ret .= '<ul>';
			foreach ($json_a["varroa"] as $treatment) {
				$ret .= '<li class="level2"><div class="li">'
					.date_format(date_create_from_format('Ymd',$treatment["start-date"]), 'd-m-Y')
					.($treatment["end-date"] != '' ? ' &rarr; '.date_format(date_create_from_format('Ymd',$treatment["end-date"]), 'd-m-Y') : '').' : '
					.'<strong>'.$treatment["medication"].'</strong> ('
					.$treatment["quantity"].')</div></li>';
			}
			$ret .= '</ul>';
		}
		$ret .= '</li>';

		$ret .= '</ul></div></div>
			<script type="text/javascript">
				jQuery(document).ready(function () {
					jQuery("#toggle-view .toggle div").click(function () {
						var text = jQuery(this).children("div.panel");
						if (text.is(":hidden")) {
							text.slideDown("200");
							jQuery(this).children("span").html("-");
						} else {
							text.slideUp("200");
							jQuery(this).children("span").html("+");
						}
					});
				});
			</script></div>';

		if (isset($INFO['userinfo'])) {
			$form = new Doku_Form(array(
				'class' => 'button btn_secedit apis__plugin',
				'id'    => 'apis__plugin' . $this->form_id));
			$form->addElement(form_makeButton('submit', '', 'Varroas', array('name' => 'apis_varroa')));
			$form->addElement(form_makeButton('submit', '', 'Nourrissement', array('name' => 'apis_feed')));
			$form->addElement(form_makeButton('submit', '', 'Hausses', array('name' => 'apis_hive')));
			$form->addElement(form_makeButton('submit', '', 'Reine', array('name' => 'apis_queen')));
			$ret .= 
				'<div class="secedit editbutton_section editbutton_0">'
					.$form->getForm()
				.'</div><hr />';
		}

		return $ret;
	}

	private function render_apis_summary() {
		$ret = '';

		if (!defined('FT_LOADED')) {
			define('FT_LOADED',true);
			$ret .= '
				<script src="/lib/plugins/apis/FooTable-2/js/footable.js" type="text/javascript"></script>
				<script src="/lib/plugins/apis/FooTable-2/js/footable.sort.js" type="text/javascript"></script>
				<link href="/lib/plugins/apis/FooTable-2/css/footable.core.css" rel="stylesheet" type="text/css" />';
		}
		
		$ret .= '
				<table id="hive-summary" class="footable">
					<thead>
						<tr>
							<th data-sort-initial="true">Id</th>
							<th>Nom</th>
							<th>Race</th>
							<th data-type="numeric">Ann&eacute;e</th>
							<th>Type</th>
							<th data-type="numeric">Taille</th>
						</tr>
					</thead>
					<tbody>';

		// use config-queens.txt & select the queens in a hive
		$qf = new queenFamily('config-queens');

		// loop on the owned queens only
		$ownedQueens = $qf->getOwnedQueens();
		$row = 0;
		foreach ($ownedQueens as $q) {
			$filename = $q['hive'];
			$jsonfilecontent = rawWiki('json:'.$filename);
			$json_a = json_decode($jsonfilecontent, true);

			$ret .= '<tr class="'.(($row++ % 2)?'odd':'even').'">
					<td class="numeric">'.$q['id'].'</td>
					<td><a href="'.$q['url'].'">'.$q['name'].'</a></td>
					<td>'.$q['race_m'].'</td>';
				
			$date = $q['birth'];
			if ($date != null) {
				$date = substr($date, 0, 4);
			}
			$ret .= '<td class="numeric">'.$date.'</td>
					<td>'.$json_a['hive']['type'].'</td>
					<td class="numeric">'.$json_a['hive']['frame_count'].'</td>
				</tr>';
		}

		$ret .= '</tbody>
				</table>
				<script type="text/javascript">
					jQuery(function () {
						jQuery(".footable").footable();
					});
				</script>';

		return $ret;
	}

	private function render_apis_eval($year) {
		$ret = '';

		if (!defined('FT_LOADED')) {
			define('FT_LOADED',true);
			$ret .= '
				<script src="/lib/plugins/apis/FooTable-2/js/footable.js" type="text/javascript"></script>
				<script src="/lib/plugins/apis/FooTable-2/js/footable.sort.js" type="text/javascript"></script>
				<link href="/lib/plugins/apis/FooTable-2/css/footable.core.css" rel="stylesheet" type="text/css" />';
		}
		
		$ret .= '<div>Fiche de rucher <strong>'.$year.'</strong></div>
				<table id="hive-eval" class="footable">
					<thead>
						<tr class="footable-group-row">
							<th data-group="group1">Identification</th>
							<th data-group="group2">Ann&eacute;e</th>
							<th data-group="group3" colspan="2">Vitalit&eacute;</th>
							<th data-group="group4">Douceur</th>
							<th data-group="group5">Tranquillit&eacute;</th>
							<th data-group="group6">Hivernage</th>
							<th data-group="group7">R&eacute;colte</th>
							<th data-group="group8" colspan="2">Race</th>
							<th data-group="group9">Essaimage</th>
							<th data-group="group10">Remarques</th>
						</tr>
						<tr>
							<th data-group="group1" data-sort-initial="true">&nbsp;</th>
							<th data-group="group2" data-type="numeric">&nbsp;</th>
							<th data-group="group3" data-type="numeric">Couvain</th>
							<th data-group="group3" data-type="numeric">Abeilles</th>
							<th data-group="group4" data-type="numeric">&nbsp;</th>
							<th data-group="group5" data-type="numeric">&nbsp;</th>
							<th data-group="group6" data-hide="phone,tablet">&nbsp;</th>
							<th data-group="group7" data-type="numeric">(kg)</th>
							<th data-group="group8" data-hide="phone,tablet">Morphologie</th>
							<th data-group="group8" data-hide="phone,tablet">Comportement</th>
							<th data-group="group9" data-hide="phone,tablet">&nbsp;</th>
							<th data-group="group10" data-hide="phone,tablet">&nbsp;</th>
						</tr>
				</thead>
					<tbody>';
		
		// use config-queens.txt & select the queens in a hive
		$qf = new queenFamily('config-queens');

		// loop on the owned queens only
		$ownedQueens = $qf->getOwnedQueens();
		$row = 0;
		foreach ($ownedQueens as $q) {
			$eval = $qf->getEval($q, $year);
			if ($eval != null) {
				$date = $q['birth'];
				if ($date != null) {
					$date = substr($date, 0, 4);
				}
				$remark = str_replace(', ', ',<br/>', $eval['remark']);	
				$ret .= '<tr class="'.(($row++ % 2)?'odd':'even').'">
						<td>'.$q['id'].' <a href="'.$q['url'].'">'.$q['name'].'</a></td>
						<td class="numeric">'.$date.'</td>
						<td class="numeric">'.$eval['vit_c'].'</td>
						<td class="numeric">'.$eval['vit_a'].'</td>
						<td class="numeric">'.$eval['douc'].'</td>
						<td class="numeric">'.$eval['tranq'].'</td>
						<td>'.$eval['hiv'].'</td>
						<td class="numeric">'.$eval['recolte'].'</td>
						<td>'.$q['race_m'].'</td>
						<td>'.$q['race_c'].'</td>
						<td>'.$eval['ess'].'</td>
						<td>'.$remark.'</td>
					</tr>';
			}
		}
			
		$ret .= '</tbody>
				</table>
				<script type="text/javascript">
					jQuery(function () {
						jQuery(".footable").footable();
					});
				</script>';
		
		return $ret;
	}

	private function render_apis_tree($year) {
		$ret = '';
		
		if (!defined('D3_LOADED')) {
			define('D3_LOADED',true);
			$qf = new queenFamily('config-queens');
			$flare = $qf->getQueensTree($year);

			$file = 'flare.json';
			file_put_contents($file, json_encode($flare));

			$ret .= '
				<a id="apisgene" href="#">Généalogie</a>
				<div id="apisdialog" title="Généalogie"><div id="apistree">&nbsp;</div></div>
				<script src="/lib/plugins/apis/d3/d3.js" type="text/javascript"></script>
				<script src="/lib/plugins/apis/d3/d3.layout.js" type="text/javascript"></script>
				<link href="/lib/plugins/apis/d3.style.css" rel="stylesheet" type="text/css" />
				<script src="/lib/plugins/apis/d3.apis.tree.js" type="text/javascript"></script>
				<script  type="text/javascript">
					jQuery("#apisdialog").dialog(
						{ autoOpen: false }
					);
					jQuery("#apisgene").click(
						function() { 
							d3.json("'.$file.'", function(json) {
								root = json;
								root.x0 = h / 2;
								root.y0 = 0;			
								update(root);
							});
							jQuery("#apisdialog").show();
							jQuery("#apisdialog").dialog("option", "width", 1024);
							jQuery("#apisdialog").dialog("open");
						}
					);
				</script>';
		} else {
			$ret .= 'only one tree per page';
		}

		return $ret;
	}
}